<template>
  <div class="fk_home">
    <div id="map" class="map"></div>
    <!-- 地图左侧 -->
    <transition name="el-fade-in-linear">
      <map-left
        class="map_left"
        v-if="isShowLeft"
        @handShowHospital="handShowHospital"
        @handleSurplus="handleSurplus"
        @sendDACRequestRes="receiveDACRequestRes"
        @showMedicalRoomEmit="handleShowMedicalRoomPoint"
        @showUserInfoEmit="handleShowUserInfo"
        @showAmbulanceEmit="handleShowAmbulance"
      ></map-left>
    </transition>
    <!-- 图例 -->
    <transition name="el-fade-in-linear">
      <div class="map_left_bottom" v-if="isShowLeft">
        <left-bottom
          @handleShowWhich="handleShowWhichPar"
          @showWhichNotGuaranteeEmit="handleShowWhichNotGuaranteeEmit"
        />
      </div>
    </transition>

    <!-- 地图右侧 -->
    <transition name="el-fade-in-linear">
      <div class="map_right">
        <map-right
          @getLinePosition="handleLinePosition"
          @clearLine="handleClearLine"
          @acceptPatientEmit="handleAceptPatient"
          @sendHospitalEmit="handleSendHospital"
        />
      </div>
    </transition>
    <!-- 医院列表 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowHospitalDialog">
        <hospital-info-dialog
          @closeHospitalEmit="handleCloseHospital"
          @hospitalNodeEmit="handleHospitalNode"
        >
        </hospital-info-dialog>
      </div>
    </transition>
    <!-- 运动员村诊所 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowAthleticalClinicDg">
        <medical-room-dialog
          :data="athleticalClinicTree"
          :medicalpointType="medicalpointType"
          @closeMedicalRoomPointEmit="handleCloseMedicalRoomPoint"
          @medicalRoomPointNodeEmit="handlemedicalRoomPointNodeClick"
          :isOnlineMedical="isOnlineMedical"
        ></medical-room-dialog>
      </div>
    </transition>
    <!-- 医务室 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowMedicalRoomDialog">
        <medical-room-dialog
          :data="medicalRoomDataTree"
          :medicalpointType="medicalpointType"
          @closeMedicalRoomPointEmit="handleCloseMedicalRoomPoint"
          @medicalRoomPointNodeEmit="handlemedicalRoomPointNodeClick"
          :isOnlineMedical="isOnlineMedical"
        ></medical-room-dialog>
      </div>
    </transition>
    <!-- FOP医疗点 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowFOPMedicalPonitDialog">
        <medical-room-dialog
          :data="FOPMedicalDataTree"
          :medicalpointType="medicalpointType"
          @closeMedicalRoomPointEmit="handleCloseMedicalRoomPoint"
          @medicalRoomPointNodeEmit="handlemedicalRoomPointNodeClick"
          :isOnlineMedical="isOnlineMedical"
        ></medical-room-dialog>
      </div>
    </transition>
    <!-- 观众医疗点 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowAudienceMedicalPonitDialog">
        <medical-room-dialog
          :data="audienceMedicalPointDataTree"
          :medicalpointType="medicalpointType"
          @closeMedicalRoomPointEmit="handleCloseMedicalRoomPoint"
          @medicalRoomPointNodeEmit="handlemedicalRoomPointNodeClick"
          :isOnlineMedical="isOnlineMedical"
        ></medical-room-dialog>
      </div>
    </transition>
    <!-- 医生 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowDoctorDialog">
        <user-info-dialog
          :data="doctorDataTree"
          :userType="userType"
          @closeUserInfoEmit="handleCloseUserInfo"
          @userInfoNodeEmit="handleUserInfoNodeClick"
          :isOnlinePerson="isOnlinePerson"
        ></user-info-dialog>
      </div>
    </transition>
    <!-- 护士 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowNurseDialog">
        <user-info-dialog
          :data="nurseDataTree"
          :userType="userType"
          @closeUserInfoEmit="handleCloseUserInfo"
          @userInfoNodeEmit="handleUserInfoNodeClick"
          :isOnlinePerson="isOnlinePerson"
        ></user-info-dialog>
      </div>
    </transition>
    <!-- 车辆 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowAmbulanceDialog">
        <ambulance-info-dialog
          :data="ambulanceDataTree"
          @closeAmbulanceInfoEmit="handleCloseAmbulanceInfo"
          @ambulanceInfoNodeEmit="handleAmbulanceInfoNode"
          :isOnlineAmb="isOnlineAmb"
        ></ambulance-info-dialog>
      </div>
    </transition>
    <!-- 药品药材不足的医疗点列表 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowDrugConsumDialog">
        <drug-consum-dialog
          :data="DACInsufficientTree"
          @closeDrugConsumEmit="closeDrugConsumClick"
          @drugconsumNodeEmit="handleDrugNodeClick"
        ></drug-consum-dialog>
      </div>
    </transition>
    <!-- 地图右侧按钮子弹窗 -->
    <transition name="el-fade-in-linear">
      <div class="show_dialog">
        <e-m-record />
        <!-- 调派弹窗 -->
        <regulation-measure />
      </div>
    </transition>
    <!-- 地图右侧 接诊病人自定义弹窗 -->
    <transition name="el-fade-in-linear">
      <div class="patient-custom-dialog" v-if="isShowAcceptPatient">
        <el-dialog
          v-model="isShowAcceptPatient"
          title="病人列表"
          width="70%"
          align-center
        >
          <accept-patient :data="acceptPatientData"></accept-patient>
        </el-dialog>
      </div>
    </transition>
    <!-- 地图右侧 送往医院自定义弹窗 和接诊病人用的是同一个自定义弹窗组件-->
    <!-- <transition name="el-fade-in-linear">
      <div class="patient-custom-dialog" v-if="isShowSendHospital">
        <send-hospital :data="sendHospitalData" @closeSendHospitalEmit="handleCloseSendHospital"></send-hospital>
      </div>
    </transition> -->
    <!-- 场馆中按钮子弹窗 -->
    <!-- 赛程弹窗组件 -->
    <game-schedule></game-schedule>
    <!-- 医疗点弹窗组件 -->
    <medical-group
      :showMedicalGroupFlag="showMedicalGroupFlag"
      :doctorData="doctorData"
      :nurseData="nurseData"
    ></medical-group>
    <!-- 场馆车辆弹窗组件 -->
    <venue-ambu
      :showVenueAmbuFlag="showVenueAmbuFlag"
      :venueAmbuData="venueAmbuData"
    ></venue-ambu>
    <!-- 场馆药品耗材弹窗组件 -->
    <venue-grugs
      :showDrugFlag="showDrugFlag"
      :DACTableData="DACTableData"
    ></venue-grugs>

    <!-- 控制先隐藏按钮 -->
    <el-button
      type=""
      plain
      @click="handleShowLeft"
      style="position: absolute; top: 5px; left: 50%"
    >
      <template #icon>
        <el-icon>
          <Hide v-if="!isShowLeft" />
          <View v-else />
        </el-icon>
      </template>
      <span>左侧栏</span>
    </el-button>

    <!-- <el-button title="清除地图上的车辆标签图层" type="" plain @click="handleHideAmbuTag"
      style="position: absolute; bottom: 5px; left: 850px">
      <template #icon>
        <el-icon>
          <DeleteFilled />
        </el-icon>
      </template>
      <span>隐藏车辆标签</span>
    </el-button> -->
    <!-- <el-button type="" plain @click="handleOrdinaryPattern" style="position: absolute; bottom: 5px; left: 900px">
      <span>普通模式</span>
    </el-button> -->
    <!-- <el-button type="" plain @click="handleDiurnalPattern" style="position: absolute; bottom: 5px; left: 1000px;">
      <span>白天模式</span>
    </el-button> -->
    <!-- <el-button type="" plain @click="handleDarkPattern" style="position: absolute; bottom: 5px; left: 1000px">
      <span>黑夜模式</span>
    </el-button> -->
  </div>
</template>

<script>
import BMapGL from 'BMapGL';
import { reactive, toRefs, onBeforeMount, onMounted, onUnmounted } from 'vue';
import { useStore } from 'vuex';
// network
import { GetHospitalInfo } from '../../network/hospital';
import {
  GetActiVenueInfo,
  GetActiVenueDetail,
  GetMatchingVenues,
} from '../../network/venues';
import { GetAmbulanceInfo } from '../../network/ambulance';
import {
  GetMedicalPointPerson,
  GetAmbList,
  GetDACList,
  GetInsufficient,
  QueryMedicalPointUserList,
  QueryNotGuaranteeAmb,
} from '../../network/hosVenAmbuListData';
// 图标弹窗
import {
  hospitalInfoContentcopy,
  venueContentcopy,
  vehicleInfoContentcopy,
  venueMedicalPointContentcopy,
  vehicleInfoContentNotGuarantee,
} from './mapIconInfojs/mapIconInfousing';
// 场馆子弹窗
import GameSchedule from '../dialog/GameSchedule.vue';
import MedicalGroup from '../dialog/MedicalGroup.vue';
import VenueAmbu from '../dialog/VenueAmbu.vue';
import VenueGrugs from '../dialog/VenueGrugs.vue';
// 地图左侧栏
import MapLeft from './component/MapLeft.vue';
// 地图右侧栏
import MapRight from './component/MapRight.vue';
// 地图右侧按钮弹窗
import EMRecord from '../dialog/EMRecord.vue';
import RegulationMeasure from '../dialog/RegulationMeasure.vue';
// 图例
import LeftBottom from './component/LeftBottom.vue';
// 自定义vuex 方法
import { setupMapState } from '../../store/utils/hook';
// 创建图标方法
import { CreateMark } from './methods/creatMarks';
// 转换经纬度
import { wgs84togcj02tobd09 } from '../../utils/84tobaiduGPS';

import { treeFormatData } from '../../modelUtils/returnModel';

import { ElMessage } from 'element-plus';
import { QueryPowerMarkLine } from '../../network/poyline';
import { GetDanBingPreVedio } from '../../network/danbingVideo';

import MedicalRoomDialog from './customDialog/MedicalRoomDialog.vue';
import UserInfoDialog from './customDialog/UserInfoDialog.vue';
import AmbulanceInfoDialog from './customDialog/AmbulanceInfoDialog.vue';
import HospitalInfoDialog from './customDialog/HospitalInfoDialog.vue';
import DrugConsumDialog from './customDialog/DrugConsumDialog.vue';

// import SendHospital from '../map/component/compChildMessage/SendHospital.vue';
import AcceptPatient from '../map/component/compChildMessage/AcceptPatient.vue';
import { styleJson1, styleJson2 } from './mapstyleJson/index';
export default {
  name: 'homeMapchanging',
  components: {
    GameSchedule,
    MedicalGroup,
    VenueAmbu,
    VenueGrugs,
    MapLeft,
    LeftBottom,
    MapRight,
    EMRecord,
    RegulationMeasure,
    MedicalRoomDialog,
    UserInfoDialog,
    AmbulanceInfoDialog,
    HospitalInfoDialog,
    DrugConsumDialog,
    // SendHospital,
    AcceptPatient,
  },
  props: [],
  beforeRouteEnter(to, from, next) {
    // console.log(to, from, next)
    next((vm) => {
      // console.log(vm.$store)
      try {
      } catch (error) {}
    });
  },
  setup() {
    //定义地图
    var map = null;
    // 实例化管理仓储
    const store = useStore();
    // console.log(store)
    // 组件内部响应式状态
    const compState = reactive({
      ambuListNotguarantee: [],
      markerList: [],
      // 场馆医疗点
      showMedicalGroupFlag: 1,
      venuePersonType: [{ venDoctor: '5', venNurse: '6' }],
      doctorData: [],
      nurseData: [],
      // 场馆车辆
      showVenueAmbuFlag: 1,
      venueAmbuData: [],
      // 场馆药品耗材
      showDrugFlag: 1,
      drugConsumType: [{ drug: 1, consum: 2 }],
      DACTableData: [],
      // 医院
      isShowHospitalDialog: false,
      // 药品耗材
      isShowDrugConsumDialog: false,
      DACInsufficientTree: [],
      // 运动员村诊所数据
      athleticalClinicTree: [],
      // 医务室/医疗点数据
      medicalRoomDataTree: [],
      // FOP医疗点数据
      FOPMedicalDataTree: [],
      // 观众医疗点数据
      audienceMedicalPointDataTree: [],
      // 医生数据
      doctorDataTree: [],
      // 护士数据
      nurseDataTree: [],
      // 车辆数据
      ambulanceDataTree: [],
      // 医疗点类型
      medicalpointType: '',
      // 人员类型
      userType: 0,
      // 运动员村诊所
      isShowAthleticalClinicDg: false,
      // 医务室显示
      isShowMedicalRoomDialog: false,
      // FOP医疗点显示
      isShowFOPMedicalPonitDialog: false,
      // 观众医疗点显示
      isShowAudienceMedicalPonitDialog: false,
      isOnlineMedical: 1,
      // 医生显示
      isShowDoctorDialog: false,
      // 护士显示
      isShowNurseDialog: false,
      isOnlinePerson: 1,
      // 车辆显示
      isShowAmbulanceDialog: false,
      // 在线车辆标志
      isOnlineAmb: 1,
      // 接收病人
      isShowSendHospital: false,
      sendHospitalData: [],
      isShowAcceptPatient: false,
      acceptPatientData: [],

      // 图例
      isShowLeft: true,
      // 定时器
      ambuTimer: null,
      // 两点之间的路线
      drivingLine: null,
      // 正在比赛的场馆
      venueView: [],

      // 车辆位置突出显示
      venueAmbu: [],
      ambuLayer: null,
      viewambu: null,
      layerdata: [],
      isShowVenueLayers: false,
    });
    const notguaranteeTaskVehicleUrl = require('../../assets/imgHome/mapIcon/notguarantee-task-vehicle.png');
    const notguaranteeOntaskVehicleUrl = require('../../assets/imgHome/mapIcon/notguarantee-ontask-vehicle.png');
    // 取store数据
    const { ACVCodesVx } = setupMapState('app', ['ACVCodesVx']);
    const { userInfoVx } = setupMapState('app', ['userInfoVx']);
    // 车辆列表
    const { ambulanceTreeRemoteVx } = setupMapState('HospVenuAmbuModule', [
      'ambulanceTreeRemoteVx',
    ]);
    // 医院
    const { hospitalTreeRemoteVx } = setupMapState('HospVenuAmbuModule', [
      'hospitalTreeRemoteVx',
    ]);
    const { venueTreeRemoteVx } = setupMapState('HospVenuAmbuModule', [
      'venueTreeRemoteVx',
    ]);
    // 创建场馆下的医疗点
    const { venueMedicalPointArrVx } = setupMapState('HospVenuAmbuModule', [
      'venueMedicalPointArrVx',
    ]);
    // 医务室
    const { medicalRooms } = setupMapState('HospVenuAmbuModule', [
      'medicalRooms',
    ]);
    // 人员
    const { doctorsVx } = setupMapState('HospVenuAmbuModule', ['doctorsVx']);
    const { nursesVx } = setupMapState('HospVenuAmbuModule', ['nursesVx']);
    // 车辆
    const { ambulancesVx } = setupMapState('HospVenuAmbuModule', [
      'ambulancesVx',
    ]);
    // 接诊病人
    const { acceptPatientVx, sendHospitalPatientVx } = setupMapState(
      'HospVenuAmbuModule',
      ['acceptPatientVx', 'sendHospitalPatientVx'],
    );
    // 选择的场馆城市信息
    const { cityInfoVx } = setupMapState('HospVenuAmbuModule', ['cityInfoVx']);
    const { venueInfoVx } = setupMapState('HospVenuAmbuModule', [
      'venueInfoVx',
    ]);
    // 非保障车辆
    const { notGuaranteeAmbVx } = setupMapState('HospVenuAmbuModule', [
      'notGuaranteeAmbVx',
    ]);
    /**
     * 事件处理方法
     * */
    // 1.初始化地图方法
    const InitMyMap = (toMapCity) => {
      // console.log(map)
      map = new BMapGL.Map('map'); // 创建地图实例
      // map.centerAndZoom(new BMapGL.Point(120.214465, 30.254098), 12); // 初始化地图，设置中心点坐标和地图级别
      map.centerAndZoom(toMapCity, 12); // 初始化地图，设置中心点坐标和地图级别
      map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      map.setHeading(30); //设置地图旋转角度

      // //监听地图点击
      // map.addEventListener('click', function (e) {
      //   // alert("点击的经纬度：" + e.latlng.lng + ", " + e.latlng.lat);
      //   // getAndSetCurCity(map);
      // });
      // // 监听地图缩放级别
      // map.addEventListener('zoomstart', function (e) {
      //   console.log(map.getZoom());
      //   createPoyline()
      // });
    };
    // 过滤节点数据
    const filterNode = (value, data) => {
      if (!value) return true;
      return data.name.includes(value);
    };
    // 清除mapvgl图层
    const handleRemoveLayers = (view) => {
      // console.log(view)
      if (view != null) view.removeAllLayers();
    };
    // 创建路线方法
    const startLuXian = (pathParams) => {
      let starPoint = new BMapGL.Point(pathParams.ambLng, pathParams.ambLat);
      let endPoint = new BMapGL.Point(pathParams.hosLng, pathParams.hosLat);
      compState.drivingLine = new BMapGL.DrivingRoute(map, {
        renderOptions: { map: map, autoViewport: true },
      });
      // console.log(starPoint, endPoint);
      compState.drivingLine.search(starPoint, endPoint);
      map.centerAndZoom(starPoint, 16);

      // 创建动态效果
    };
    //********************** 左侧栏医院操作*/
    // 点击显示医院列表
    const handShowHospital = () => {
      // 关闭其他
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseUserInfo({ type: compState.userType });
      handleCloseAmbulanceInfo();
      closeDrugConsumClick();

      // 显示
      compState.isShowHospitalDialog = true;
    };
    // 点击医院跳转
    const handleHospitalNode = (node) => {
      console.log('医院节点', node);
      map.flyTo(new BMapGL.Point(node.lng, node.lat), 17);
    };
    // 关闭定点医院信息列表
    const handleCloseHospital = () => {
      compState.isShowHospitalDialog = false;
    };
    //********************** 左侧栏药品耗材操作*/
    // 点击显示药品耗材医疗点列表
    const handleSurplus = (val) => {
      // console.log(val)
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseUserInfo({ type: compState.userType });
      handleCloseAmbulanceInfo();
      handleCloseHospital();
      // 显示
      compState.isShowDrugConsumDialog = val;
    };
    // 点击医疗点节点
    const handleDrugNodeClick = async (node) => {
      // console.log(node)
      let medicalId = node.id;
      compState.DACTableData = [];
      // 药品数据
      let drugList = await GetInsufficient({ mpCode: medicalId, type: 1 });
      // console.log("1", drugList);
      if (drugList.length > 0) {
        drugList.forEach((item) => {
          item.percentage = item.percentage + '%';
        });
        compState.DACTableData.push({ drug: drugList });
      }
      // 耗材数据
      let consumList = await GetInsufficient({ mpCode: medicalId, type: 2 });
      // console.log("2", consumList);
      if (consumList.length > 0) {
        consumList.forEach((item) => {
          item.percentage = item.percentage + '%';
        });
        compState.DACTableData.push({ consum: consumList });
      }
      // console.log('compState.DACTableData', compState.DACTableData)
      compState.showDrugFlag++;
    };
    // 关闭医疗点列表
    const closeDrugConsumClick = () => {
      compState.isShowDrugConsumDialog = false;
    };
    //********************** 左侧栏医务室/医疗点操作*/
    const handleShowMedicalRoomPoint = (obj) => {
      console.log(obj);
      let { type, val } = obj;
      compState.isOnlineMedical = val;
      // 赋值传给子组件
      compState.medicalpointType = type;
      // 关闭其他弹窗
      handleCloseHospital();
      handleCloseUserInfo(compState.userType);
      handleCloseAmbulanceInfo();
      closeDrugConsumClick();
      if (type == 'MedicalPointType-1') {
        //场馆医务室
        compState.isShowFOPMedicalPonitDialog = false;
        compState.isShowAudienceMedicalPonitDialog = false;
        compState.isShowAthleticalClinicDg = false;
        // 显示
        // compState.medicalRoomDataTree = medicalRooms
        compState.isShowMedicalRoomDialog = true;
      } else if (type == 'MedicalPointType-2') {
        //FOP医疗点
        compState.isShowMedicalRoomDialog = false;
        compState.isShowAudienceMedicalPonitDialog = false;
        compState.isShowAthleticalClinicDg = false;
        // 显示
        compState.isShowFOPMedicalPonitDialog = true;
      } else if (type == 'MedicalPointType-3') {
        //观众医疗点
        compState.isShowFOPMedicalPonitDialog = false;
        compState.isShowMedicalRoomDialog = false;
        compState.isShowAthleticalClinicDg = false;
        // 显示
        compState.isShowAudienceMedicalPonitDialog = true;
      } else {
        compState.isShowFOPMedicalPonitDialog = false;
        compState.isShowMedicalRoomDialog = false;
        compState.isShowAudienceMedicalPonitDialog = false;
        compState.isShowAthleticalClinicDg = true;
      }
    };
    const handlemedicalRoomPointNodeClick = (node) => {
      console.log('医疗点节点');
      let LngLatObj = wgs84togcj02tobd09(node.Lng, node.Lat);
      map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 19);
    };
    const handleCloseMedicalRoomPoint = ({ type }) => {
      if (type == 'MedicalPointType-1') {
        //场馆医务室
        compState.isShowMedicalRoomDialog = false;
      } else if (type == 'MedicalPointType-2') {
        //FOP医疗点
        compState.isShowFOPMedicalPonitDialog = false;
      } else if (type == 'MedicalPointType-3') {
        //观众医疗点
        compState.isShowAudienceMedicalPonitDialog = false;
      } else {
        compState.isShowAthleticalClinicDg = false;
      }
    };
    //********************** 左侧栏医生/护士点操作*/
    const handleShowUserInfo = ({ type, val }) => {
      // 赋值传给子组件
      compState.userType = type;
      compState.isOnlinePerson = val;
      // console.log(compState.userType)
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseAmbulanceInfo();
      handleCloseHospital();
      closeDrugConsumClick();
      if (type == 5) {
        //医生
        compState.isShowNurseDialog = false;
        // 显示
        // compState.doctorDataTree = doctorsVx
        compState.isShowDoctorDialog = true;
      } else {
        //护士
        compState.isShowDoctorDialog = false;
        // 显示
        // compState.nurseDataTree = nursesVx
        compState.isShowNurseDialog = true;
      }
    };
    const handleUserInfoNodeClick = (node) => {
      // 不做处理
      console.log('人员节点');
    };
    const handleCloseUserInfo = ({ type }) => {
      if (type == 5) {
        compState.isShowDoctorDialog = false;
      } else {
        compState.isShowNurseDialog = false;
      }
    };
    //********************** 左侧栏车辆操作*/
    const handleShowAmbulance = async (val) => {
      // console.log(val)
      // 关闭其他
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseUserInfo({ type: compState.userType });
      handleCloseHospital();
      closeDrugConsumClick();
      // 显示
      compState.isShowAmbulanceDialog = true;
      compState.isOnlineAmb = val;
      // compState.ambulanceDataTree = ambulancesVx
    };
    const handleAmbulanceInfoNode = (node) => {
      console.log('车辆节点');
      // console.log(node)
      let LngLatObj = wgs84togcj02tobd09(node.Lng, node.Lat);
      map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 19);
    };
    const handleCloseAmbulanceInfo = () => {
      compState.isShowAmbulanceDialog = false;
    };

    //**********************  接诊和送往点击事件  */
    const handleAceptPatient = async () => {
      await store.dispatch('HospVenuAmbuModule/getAcceptPatient', { type: 1 });
      compState.acceptPatientData = acceptPatientVx;
      compState.isShowAcceptPatient = true;
    };
    const handleSendHospital = async () => {
      await store.dispatch('HospVenuAmbuModule/getAcceptPatient', { type: 2 });
      compState.acceptPatientData = sendHospitalPatientVx;
      compState.isShowAcceptPatient = true;
    };
    const handleCloseSendHospital = () => {
      state.isShowSendHospital = false;
    };
    // 药品耗材tree
    const receiveDACRequestRes = (data) => {
      // console.log("药品耗材tree", data)
      compState.DACInsufficientTree = treeFormatData(data);
    };

    //********************** 左侧栏图例显隐藏 */
    const handleShowWhichPar = (val) => {
      // // 显示哪类图标
      // console.log(val)
      //#region  医院

      let hospitals = val.filter((item) => item.flag == 'hospital');
      let overlaysHospital = map
        .getOverlays()
        .filter((item) => item.clas == 'hospital');
      if (hospitals.length > 0) {
        // 显示
        // 判断医院覆盖物是否存在，存在则显示调用show方法，不存在则创建
        if (overlaysHospital.length > 0) {
          console.log('overlaysHospital show');
          overlaysHospital.forEach((item) => item.show());
        } else {
          // console.log('hospitalTreeRemoteVx', hospitalTreeRemoteVx)
          hospitalTreeRemoteVx.value.forEach((item) => {
            // 转换经纬度
            var hospitalIconUrl = require('../../assets/imgHome/mapIcon/hospital.png'); //医院图标
            let marker = CreateMark(
              hospitalIconUrl,
              35,
              35,
              item.lng,
              item.lat,
              'hospital',
              item.id,
            );
            let lng = item.lng;
            let lat = item.lat;
            // 图标存进数组
            compState.markerList.push(marker);
            // 监听图标点击
            marker.addEventListener('click', function () {
              // console.log(marker)
              var hospid = marker.id;
              // 根据id找到此医院
              let curMark = hospitalTreeRemoteVx.value.filter((item) => {
                return item.id == hospid;
              });
              // 设置中心点坐标和地图级别
              map.flyTo(new BMapGL.Point(lng, lat), 18);
              // console.log(curMark[0])
              let opts = {
                title: '医院信息',
                width: 400,
                height: 'auto',
              };
              let myinfoWindow = new BMapGL.InfoWindow(
                hospitalInfoContentcopy(curMark[0]),
                opts,
              );
              this.openInfoWindow(myinfoWindow);
            });
            // 1s后将医院图标添加到地图
            let timer = setTimeout(() => {
              map.addOverlay(marker);
              clearTimeout(timer);
            }, 500);
          });
        }
      } else {
        //不显示
        console.log('overlaysHospital hide');
        overlaysHospital.forEach((item) => item.hide());
      }

      //#endregion

      //#region 场馆

      let venues = val.filter((item) => item.flag == 'venue');
      let overlaysVenue = map
        .getOverlays()
        .filter((item) => item.clas == 'venue');
      // console.log('venueTreeRemoteVx', venueTreeRemoteVx)
      if (venues.length > 0) {
        // console.log('venues', venues)
        if (overlaysVenue.length > 0) {
          console.log('overlaysVenue show');
          overlaysVenue.forEach((item) => item.show());
        } else {
          let venueIconUrl = require('../../assets/imgHome/mapIcon/venue.png'); //场馆图标
          venueTreeRemoteVx.value.forEach((item) => {
            // 转换经纬度
            let lng = item.lng;
            let lat = item.lat;
            let marker = CreateMark(
              venueIconUrl,
              35,
              35,
              lng,
              lat,
              'venue',
              item.id,
            );
            // 图标存进数组
            compState.markerList.push(marker);
            // 监听图标点击
            marker.addEventListener('click', async function () {
              // console.log(marker)
              var venueid = marker.id;
              // 根据id找到此场馆
              let curMark = venueTreeRemoteVx.value.filter(
                (item) => item.id == venueid,
              );
              // 设置中心点坐标和地图级别
              map.flyTo(new BMapGL.Point(lng, lat), 18);
              // console.log(curMark[0])
              let opts = {
                title: '场馆信息',
                width: 400,
                height: 'auto',
              };

              // 根据场馆id获取场馆详情
              let venueDetail = await GetActiVenueDetail({
                venuesCode: venueid,
              });
              // console.log(venueDetail)
              if (venueDetail != null) {
                await store.dispatch(
                  'HospVenuAmbuModule/saveVenueDetailAct',
                  venueDetail,
                );
              }
              let myinfoWindow = new BMapGL.InfoWindow(
                venueContentcopy({
                  curMark: curMark[0],
                  venueDetail: venueDetail,
                }),
                opts,
              );
              // 监听弹窗打开，再根据dom元素监听按钮点击
              myinfoWindow.addEventListener('open', function () {
                console.log('myinfoWindow is open');
                // 在这里移除车辆图标图层
                if (compState.viewambu != null) {
                  compState.viewambu.removeAllLayers();
                }
                // console.log(myinfoWindow.isOpen())
                let medicalGroupDoc =
                  document.getElementById('medicalGroupClick');
                let ambulanceDoc = document.getElementById('ambulanceClick');
                let drugDoc = document.getElementById('drugClick');
                // 医疗点按钮
                if (medicalGroupDoc.id == 'medicalGroupClick') {
                  medicalGroupDoc.onclick = async () => {
                    console.log('medicalGroupClick');
                    // 获取场馆医疗点数据(医生，护士都取出来)
                    // console.log(venueid);
                    let medicalPointDoctor = await GetMedicalPointPerson({
                      venuesCode: venueid,
                      personType: compState.venuePersonType[0].venDoctor,
                    });
                    let medicalPointNurse = await GetMedicalPointPerson({
                      venuesCode: venueid,
                      personType: compState.venuePersonType[0].venNurse,
                    });
                    compState.doctorData = medicalPointDoctor;
                    compState.nurseData = medicalPointNurse;
                    // console.log('医生和护士', compState.doctorData, compState.nurseData)
                    compState.showMedicalGroupFlag++;
                  };
                }
                // 车辆按钮
                if (ambulanceDoc.id == 'ambulanceClick') {
                  // 单击显示车辆列表
                  ambulanceDoc.onclick = async () => {
                    console.log('ambulanceClick');
                    // console.log(venueid)
                    let venueAmbulance = await GetAmbList({
                      venuesCode: venueid,
                    });
                    compState.venueAmbuData = venueAmbulance;
                    // console.log(compState.medicalPointAmbuData)
                    compState.showVenueAmbuFlag++;
                  };
                }
                // 药品耗材按钮
                if (drugDoc.id == 'drugClick') {
                  drugDoc.onclick = async () => {
                    console.log('drugClick');
                    // console.log(venueid)
                    compState.DACTableData = [];
                    // 药品
                    let medicalPointDrug = await GetDACList({
                      venuesCode: venueid,
                      type: compState.drugConsumType[0].drug,
                    });
                    // console.log(medicalPointDrug);
                    if (medicalPointDrug.length > 0) {
                      medicalPointDrug.forEach((item) => {
                        item.percentage = item.percentage + '%';
                      });
                      compState.DACTableData.push({ drug: medicalPointDrug });
                    }
                    // 耗材
                    let medicalPointConsum = await GetDACList({
                      venuesCode: venueid,
                      type: compState.drugConsumType[0].consum,
                    });
                    if (medicalPointConsum.length > 0) {
                      medicalPointConsum.forEach((item) => {
                        item.percentage = item.percentage + '%';
                      });
                      compState.DACTableData.push({
                        consum: medicalPointConsum,
                      });
                    }
                    compState.showDrugFlag++;
                  };
                }
              });
              // 信息窗口关闭的时候可以实时监听到
              myinfoWindow.addEventListener('close', function () {
                console.log('myinfoWindow', 'close', myinfoWindow.isOpen());
                if (compState.viewambu != null) {
                  // compState.viewambu.removeAllLayers();
                }
              });
              // 先进行事件监听 然后才打开图标弹窗********
              marker.openInfoWindow(myinfoWindow);
            });
            // 1s后将场馆图标添加到地图
            let timer = setTimeout(() => {
              map.addOverlay(marker);
              clearTimeout(timer);
            }, 600);
          });
        }
      } else {
        overlaysVenue.forEach((item) => item.hide());
      }

      //#endregion

      // #region 在线医疗点(初始化已经创建)
      let venueMedicalPointsOnline = val.filter(
        (item) => item.flag == 'venue-medical-point-online',
      );
      let overlaysvenueMedicalPointsOnline = map
        .getOverlays()
        .filter((item) => item.clas == 'venue-medical-point-online');
      if (venueMedicalPointsOnline.length > 0) {
        overlaysvenueMedicalPointsOnline.forEach((item) => item.show());
      } else {
        console.log('overlaysvenueMedicalPointsOnline hide');
        // console.log('first', overlaysvenueMedicalPointsOffline[0].getLabel())
        overlaysvenueMedicalPointsOnline.forEach((item) => {
          item.getLabel()._visible = false;
          item.hide();
        });
      }
      // #endregion

      //#region 离线医疗点

      let venueMedicalPointsOffline = val.filter(
        (item) => item.flag == 'venue-medical-point-offline',
      );
      let overlaysvenueMedicalPointsOffline = map
        .getOverlays()
        .filter((item) => item.clas == 'venue-medical-point-offline');
      if (venueMedicalPointsOffline.length > 0) {
        if (overlaysvenueMedicalPointsOffline.length > 0) {
          console.log('overlaysvenueMedicalPointsOffline show');
          overlaysvenueMedicalPointsOffline.forEach((item) => item.show());
        } else {
          let venueMedicalPointIconUrl = require('../../assets/imgHome/mapIcon/医疗点-1.png');
          var venueMedicalPointIconUrl_offLine = require('../../assets/imgHome/mapIcon/医疗点-灰1.png');
          venueMedicalPointArrVx.value.forEach((item) => {
            // console.log(item)
            let color = '#767676';
            let iconUrl = venueMedicalPointIconUrl_offLine;
            // 非在线医疗点
            if (!item.online) {
              iconUrl = venueMedicalPointIconUrl_offLine;
              color = '#767676';
            } else {
              iconUrl = venueMedicalPointIconUrl;
              color = '#9933ff';
            }
            let marker = CreateMark(
              iconUrl,
              50,
              50,
              item.lng,
              item.lat,
              'venue-medical-point-offline',
              item.id,
              item.name,
              undefined,
              color,
            );
            // 图标存进数组
            compState.markerList.push(marker);
            // 监听图标点击
            marker.addEventListener('click', async function () {
              // console.log(marker)
              var venueMedicalPointid = marker.id;
              let medicalInfo = {};
              await QueryMedicalPointUserList({
                medicalPointCode: venueMedicalPointid,
              })
                .then((res) => {
                  // console.log(res)
                  medicalInfo = res;
                })
                .catch((err) => {
                  console.log(err);
                });
              // 设置中心点坐标和地图级别
              map.flyTo(new BMapGL.Point(item.lng, item.lat), 20);
              let opts = {
                title: '医疗点信息',
                width: 300,
                height: 'auto',
              };
              let myinfoWindow = new BMapGL.InfoWindow(
                venueMedicalPointContentcopy(medicalInfo),
                opts,
              );
              this.openInfoWindow(myinfoWindow);
            });
            // 1s后将医院图标添加到地图
            let timer = setTimeout(() => {
              map.addOverlay(marker);
              clearTimeout(timer);
            }, 600);
          });
        }
      } else {
        console.log('overlaysvenueMedicalPointsOffline hide');
        // console.log('first', overlaysvenueMedicalPointsOffline[0].getLabel())
        overlaysvenueMedicalPointsOffline.forEach((item) => {
          item.getLabel()._visible = false;
          item.hide();
        });
      }

      //#endregion

      //#region 暂停调用车辆

      let notaskvehicles = val.filter((item) => item.flag == 'notaskvehicle');
      let overlaysnotaskvehicle = map
        .getOverlays()
        .filter((item) => item.clas == 'notaskvehicle');
      if (notaskvehicles.length > 0) {
        if (overlaysnotaskvehicle.length > 0) {
          console.log('overlaysnotaskvehicle show');
          overlaysnotaskvehicle.forEach((item) => item.show());
        } else {
          // let notaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/notask-vehicle.png'); // 暂停车图标
          // let taskVehicleIconUrl = require('../../assets/imgHome/mapIcon/task-vehicle.png'); //任务小车图标
          // let ontaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/on-vehicle.png'); // 待命小车图标
          // let notaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/notask-vehicle_yc.png'); // 暂停车图标
          // let taskVehicleIconUrl = require('../../assets/imgHome/mapIcon/task-vehicle_yc.png'); //任务小车图标
          // let ontaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/on-vehicle_yc.png'); // 待命小车图标

          let notaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/notask-vehicle_dxhd.png'); // 暂停车图标
          let taskVehicleIconUrl = require('../../assets/imgHome/mapIcon/task-vehicle_dxhd.png'); //任务小车图标
          let ontaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/on-vehicle_dxhd.png'); // 待命小车图标
          ambulanceTreeRemoteVx.value.forEach((item) => {
            // 默认是暂停调用
            let vihicleFlag = 'notaskvehicle';
            let vehicleIconUrl = notaskVehicleIconUrl;
            // 根据任务状态判断
            if (item.IsOnline == 1) {
              switch (item.StateCode) {
                // 任务中
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 101:
                case 102:
                  vihicleFlag = 'taskvehicle';
                  vehicleIconUrl = taskVehicleIconUrl;
                  // console.log(item);
                  break;
                // 待命中
                case 6:
                case 7:
                  vihicleFlag = 'onvehicle';
                  vehicleIconUrl = ontaskVehicleIconUrl;
                  break;
                default:
                  break;
              }
            } else {
              vihicleFlag = 'notaskvehicle';
              vehicleIconUrl = notaskVehicleIconUrl;
            }
            // 转换经纬度
            let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat);
            if (vihicleFlag == 'notaskvehicle') {
              let marker = CreateMark(
                vehicleIconUrl,
                // 70,
                // 70,
                30,
                45,
                LngLatObj.Lng,
                LngLatObj.Lat,
                vihicleFlag,
                item.Code,
                item.Name,
                item.Direction,
              );
              compState.markerList.push(marker);
              marker.addEventListener('click', function () {
                // console.log(marker)
                var vehicleid = marker.id;
                // 根据id找到此车辆
                let ambuCurMark = ambulanceTreeRemoteVx.value.filter(
                  (it) => it.Code == vehicleid,
                );
                // 设置中心点坐标和地图级别
                map.flyTo(
                  new BMapGL.Point(marker.latLng.lng, marker.latLng.lat),
                  20,
                );
                // console.log(ambuCurMark[0])
                let opts = {
                  title: '车辆信息',
                  width: 300,
                  height: 'auto',
                };
                let ambuInfoWindow = new BMapGL.InfoWindow(
                  vehicleInfoContentcopy(ambuCurMark[0]),
                  opts,
                );
                // 监听弹窗打开，再根据dom元素监听按钮点击
                ambuInfoWindow.addEventListener('open', function () {
                  console.log('车辆窗口打开了');
                  let vehicleMonitoringDoc = document.getElementById(
                    'vehicleMonitoringClick',
                  );
                  vehicleMonitoringDoc.onclick = () => {
                    console.log('vehiclemonitoringDoc');
                    GetDanBingPreVedio({ code: vehicleid })
                      .then((res) => {
                        // console.log('车载', res);
                        if (res) {
                          window.open(res);
                        } else {
                          ElMessage({
                            message: '暂无车载监控！',
                            type: 'warning',
                          });
                        }
                      })
                      .catch((err) => {
                        ElMessage({
                          message: '暂无车载监控！',
                          type: 'warning',
                        });
                      });
                  };
                });
                marker.openInfoWindow(ambuInfoWindow);
              });
              let timer = setTimeout(() => {
                map.addOverlay(marker);
                clearTimeout(timer);
              }, 700);
            }
          });
        }
      } else {
        console.log('overlaysnotaskvehicle hide');
        overlaysnotaskvehicle.forEach((item) => {
          item.getLabel()._visible = false;
          item.hide();
        });
      }

      //#endregion

      // 获取地图上的图标任务和待命车
      let ontaskOrtaskVehicles = val.filter(
        (item) => item.flag == 'taskvehicle' || item.flag == 'onvehicle',
      );
      let overlays = map
        .getOverlays()
        .filter(
          (item) => item.clas == 'taskvehicle' || item.clas == 'onvehicle',
        );
      if (ontaskOrtaskVehicles.length > 0) {
        let showArr = [];
        let hideArr = [];
        // 取要显示的图标(根据flag)
        ontaskOrtaskVehicles.forEach((valItem) => {
          let showIcons = overlays.filter((overlaysItem) => {
            return valItem.flag == overlaysItem.clas;
          });
          showArr.push(...showIcons);
        });
        // 取隐藏的图标(根据项)
        hideArr = overlays.filter((overlaysItem) => {
          return showArr.indexOf(overlaysItem) === -1;
        });
        // console.log("显示的图标：", showArr, "隐藏的图标：", hideArr)
        // 处理隐藏和显示
        showArr.forEach((item) => {
          item.show();
        });
        hideArr.forEach((item) => {
          item.getLabel()._visible = false;
          item.hide();
        });
      } else {
        // console.log("隐藏所有图标")
        overlays.forEach((item) => {
          item.getLabel()._visible = false;
          item.hide();
        });
      }
    };
    // 接收非保障子组件事件
    const handleShowWhichNotGuaranteeEmit = async (payload) => {
      // console.log('payload/handleShowWhichNotGuaranteeEmit', payload.length)
      // console.log('notGuaranteeAmbVx', notGuaranteeAmbVx)
      // 1.先移除非保障车辆图层
      // 获取地图上的非保障车辆图标
      let overlays = map.getOverlays().filter((item) => {
        return (
          item.clas == 'notguarantee-task-vehicle' ||
          item.clas == 'notguarantee-ontask-vehicle'
        );
      });
      // 如果存在判断显隐藏
      if (overlays && overlays.length > 0) {
        overlays.forEach((item) => {
          map.removeOverlay(item);
        });
      } else {
        // 不存在创建
      }

      // 存在要选择显示的车辆
      if (payload.length > 0) {
        // 2.根据要显示的图层创建车辆图标
        if (payload.length == 1) {
          compState.ambuListNotguarantee = notGuaranteeAmbVx.value.filter(
            (item) => item.ambStateCode == payload[0].statusCode,
          );
        } else {
          compState.ambuListNotguarantee = notGuaranteeAmbVx.value;
        }
        // console.log('compState.ambuListNotguarantee', compState.ambuListNotguarantee)

        compState.ambuListNotguarantee.forEach((item) => {
          // 转换经纬度
          let LngLatObj = wgs84togcj02tobd09(item.ambLng, item.ambLat);
          // 默认是待命中
          let vihicleFlag = 'notguarantee-ontask-vehicle';
          let vehicleIconUrl = notguaranteeOntaskVehicleUrl;
          // 根据任务状态判断
          switch (item.ambStateCode) {
            // 任务中
            case 1:
              vihicleFlag = 'notguarantee-task-vehicle';
              vehicleIconUrl = notguaranteeTaskVehicleUrl;
              // console.log(item);
              break;
            // 待命中
            case 2:
              vihicleFlag = 'notguarantee-ontask-vehicle';
              vehicleIconUrl = notguaranteeOntaskVehicleUrl;
              break;
            default:
              break;
          }
          // console.log('item', item)
          let marker = CreateMark(
            vehicleIconUrl,
            17,
            34,
            LngLatObj.Lng,
            LngLatObj.Lat,
            vihicleFlag,
            item.ambCode,
            item.ambName,
            item.ambDirection,
          );
          compState.markerList.push(marker);
          marker.addEventListener('click', function () {
            console.log(marker);
            let vehicleid = marker.id;
            // 根据id找到此车辆
            let ambuCurMark = compState.ambuListNotguarantee.filter(
              (it) => it.ambCode == vehicleid,
            );
            console.log('ambuCurMark ambuListNotguarantee', ambuCurMark);
            // 设置中心点坐标和地图级别
            map.flyTo(
              new BMapGL.Point(marker.latLng.lng, marker.latLng.lat),
              20,
            );
            let opts = {
              title: '非保障车辆信息',
              width: 300,
              height: 'auto',
            };
            let ambuInfoWindow = new BMapGL.InfoWindow(
              vehicleInfoContentNotGuarantee(ambuCurMark[0]),
              opts,
            );
            marker.openInfoWindow(ambuInfoWindow);
          });
          let timer = setTimeout(() => {
            map.addOverlay(marker);
            clearTimeout(timer);
          }, 750);
        });
      } else {
        // 如果没有选  不做处理
      }
    };
    //********************** 右侧栏*/
    // 查看线路
    const handleLinePosition = (data) => {
      // console.log(data);
      if (compState.drivingLine == null) {
        startLuXian(data);
      } else {
        compState.drivingLine.clearResults();
        startLuXian(data);
      }
    };
    // 清除线路
    const handleClearLine = (data) => {
      if (data && compState.drivingLine != null) {
        compState.drivingLine.clearResults();
      }
    };

    // 左侧显隐藏按钮
    const handleShowLeft = () => {
      compState.isShowLeft = !compState.isShowLeft;
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseUserInfo({ type: compState.userType });
      handleCloseHospital();
      handleCloseAmbulanceInfo();
    };
    // 车标签图层隐藏按钮
    const handleHideAmbuTag = () => {
      handleRemoveLayers(compState.viewambu);
      compState.isShowVenueLayers = false;
    };

    const createPoylineItemFun = (
      param,
      map,
      color,
      strokeWeight,
      strokeOpacity,
      strokeStyle,
    ) => {
      // console.log(param)
      let arr = [];
      param.forEach((item) => {
        // console.log(item['Lng'])
        arr.push(new BMapGL.Point(item['lng'], item['lat']));
      });
      var polyline = new BMapGL.Polyline(arr, {
        strokeColor: color,
        strokeWeight: strokeWeight,
        strokeOpacity: strokeOpacity,
        strokeStyle: strokeStyle,
      }); //创建折线
      map.addOverlay(polyline);
    };

    // 地图模式
    const handleOrdinaryPattern = () => {
      map.setMapStyleV2({
        styleJson: {},
      });
    };
    const handleDiurnalPattern = () => {
      map.setMapStyleV2({
        styleJson: styleJson1,
      });
    };
    const handleDarkPattern = () => {
      map.setMapStyleV2({
        styleJson: styleJson2,
      });
    };
    /**
     * 工具方法
     * 定时器
     */
    // 延时器
    const sleep = (ms) => {
      return new Promise((resolve) => {
        setTimeout(resolve, ms);
      });
    };

    // 组件挂载前
    onBeforeMount(() => {});
    // 组件挂载后
    onMounted(() => {
      // 获取当前城市
      let toMapCity =
        store.state.app.cityNameVx != ''
          ? store.state.app.cityNameVx
          : '北京市';
      //自定义图标
      // var taskVehicleIconUrl = require('../../assets/imgHome/mapIcon/task-vehicle.png'); //任务小车图标
      // var ontaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/on-vehicle.png'); // 待命小车图标
      // var notaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/notask-vehicle.png'); // 暂停车图标
      // var taskVehicleIconUrl = require('../../assets/imgHome/mapIcon/task-vehicle_yc.png'); //任务小车图标
      // var ontaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/on-vehicle_yc.png'); // 待命小车图标
      // var notaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/notask-vehicle_yc.png'); // 暂停车图标

      var taskVehicleIconUrl = require('../../assets/imgHome/mapIcon/task-vehicle_dxhd.png'); //任务小车图标
      var ontaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/on-vehicle_dxhd.png'); // 待命小车图标
      var notaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/notask-vehicle_dxhd.png'); // 暂停车图标
      var venueMedicalPointIconUrl = require('../../assets/imgHome/mapIcon/医疗点-1.png'); //场馆内医疗点图标
      var venueMedicalPointIconUrl_noLine = require('../../assets/imgHome/mapIcon/医疗点-灰1.png');

      // 初始化地图
      InitMyMap(toMapCity);

      // 之前地图加载不出来的异常的处理
      // await sleep(1500)

      /**
       * 监听map.centerAndZoom()方法的执行
       */
      map.addEventListener('load', async function (e) {
        console.log('map load');
        // 判断是否选择了全部的场馆  -1代表的是全部场馆
        if (ACVCodesVx.value.venueCode == -1) {
          ACVCodesVx.value.venueCode = userInfoVx.value.venueCode;
        }
        // console.log(ACVCodesVx.value)
        let param = ACVCodesVx.value;
        // console.log(param)
        try {
          //#region 医院数据

          GetHospitalInfo(param)
            .then((res) => {
              // console.log(res)
              if (res && res.length != 0) {
                // 缓存医院数据到vuex
                store.dispatch('HospVenuAmbuModule/saveHospitalAct', res);
              } else {
                console.log('homeMap/GetHospitalInfo', '医院数据返回为空');
              }
            })
            .catch((err) => {
              console.log('homeMap/GetHospitalInfo', err);
            });

          //#endregion

          //#region 车辆数据及图标创建

          GetAmbulanceInfo(param)
            .then((res) => {
              // console.log(res)
              if (res && res.length != 0) {
                store.dispatch('HospVenuAmbuModule/saveAmbulanceAct', res);
                res.forEach((item) => {
                  // console.log(item.IsOnline)
                  // 转换经纬度
                  let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat);
                  // 默认是暂停调用
                  let vihicleFlag = 'notaskvehicle';
                  let vehicleIconUrl = notaskVehicleIconUrl;
                  // 根据任务状态判断
                  if (item.IsOnline == 1) {
                    switch (item.StateCode) {
                      // 任务中
                      case 0:
                      case 1:
                      case 2:
                      case 3:
                      case 4:
                      case 5:
                      case 101:
                      case 102:
                        vihicleFlag = 'taskvehicle';
                        vehicleIconUrl = taskVehicleIconUrl;
                        // console.log(item);
                        break;
                      // 待命中
                      case 6:
                      case 7:
                        vihicleFlag = 'onvehicle';
                        vehicleIconUrl = ontaskVehicleIconUrl;
                        break;
                      default:
                        break;
                    }
                    // 只初始化创建任务和待命车
                    if (
                      vihicleFlag == 'taskvehicle' ||
                      vihicleFlag == 'onvehicle'
                    ) {
                      // console.log('1', 1)
                      let marker = CreateMark(
                        vehicleIconUrl,
                        // 70,
                        // 70,
                        30,
                        45,
                        LngLatObj.Lng,
                        LngLatObj.Lat,
                        vihicleFlag,
                        item.Code,
                        item.Name,
                        item.Direction,
                      );
                      compState.markerList.push(marker);
                      // console.log('marker', marker)
                      marker.addEventListener('click', function () {
                        // console.log(marker)
                        var vehicleid = marker.id;
                        // 根据id找到此车辆
                        let ambuCurMark = res.filter(
                          (it) => it.Code == vehicleid,
                        );
                        // 设置中心点坐标和地图级别
                        map.flyTo(
                          new BMapGL.Point(
                            marker.latLng.lng,
                            marker.latLng.lat,
                          ),
                          20,
                        );
                        // console.log(ambuCurMark[0])
                        let opts = {
                          title: '车辆信息',
                          width: 300,
                          height: 'auto',
                        };
                        let ambuInfoWindow = new BMapGL.InfoWindow(
                          vehicleInfoContentcopy(ambuCurMark[0]),
                          opts,
                        );
                        // 监听弹窗打开，再根据dom元素监听按钮点击
                        ambuInfoWindow.addEventListener('open', function () {
                          console.log('车辆窗口打开了');
                          let vehicleMonitoringDoc = document.getElementById(
                            'vehicleMonitoringClick',
                          );
                          vehicleMonitoringDoc.onclick = () => {
                            console.log('vehiclemonitoringDoc');
                            GetDanBingPreVedio({ code: vehicleid })
                              .then((res) => {
                                console.log('车载', res);
                                if (res) {
                                  window.open(res);
                                } else {
                                  ElMessage({
                                    message: '暂无车载监控！',
                                    type: 'warning',
                                  });
                                }
                              })
                              .catch((err) => {
                                ElMessage({
                                  message: '暂无车载监控！',
                                  type: 'warning',
                                });
                              });
                          };
                        });
                        marker.openInfoWindow(ambuInfoWindow);
                      });
                      let timer = setTimeout(() => {
                        map.addOverlay(marker);
                        clearTimeout(timer);
                      }, 700);
                    }
                  }
                });
              } else {
                console.log('homeMap/GetAmbulanceInfo', '车辆数据返回为空');
              }
            })
            .catch((err) => {
              console.log(err);
            });

          //#endregion

          //#region 获取正在举行的场馆并在地图标注

          GetMatchingVenues(param)
            .then((res) => {
              // console.log(res);
              // 存正在比赛场馆的经纬度
              var lngAndLats = [];
              if (res.length > 0) {
                res.forEach((item) => {
                  lngAndLats.push({ lng: item.Lng, lat: item.Lat });
                });
                compState.venueView = new mapvgl.View({
                  map: map,
                });
                var colors = ['#f00', '#ff0', '#0ff', '#00f'];
                var data = lngAndLats.map((item, index) => {
                  let newItem = wgs84togcj02tobd09(item.lng, item.lat);
                  // console.log(newItem);
                  return {
                    geometry: {
                      type: 'Point',
                      coordinates: [newItem.Lng, newItem.Lat],
                    },
                    color: colors[0],
                    // 圆的半径
                    size: 5,
                  };
                });
                var bubbleLayer = new mapvgl.CircleLayer({
                  // 绘制带泡泡的圆
                  type: 'bubble',
                  size: (size) => 1 * size,
                  // 扩散半径，支持直接设置和回调两种形式，size为点的大小
                  radius(size) {
                    return 5 * size;
                  },
                  // 扩散时间
                  duration: 1,
                  // 渐隐时间
                  trail: 1,
                });
                compState.venueView.addLayer(bubbleLayer);
                bubbleLayer.setData(data);
              } else {
                console.log('没有正在举办比赛的场馆！');
              }
            })
            .catch((err) => {
              console.log('homeMap/GetMatchingVenues', err);
            });

          //#endregion

          //#region 取poyline 绘制的线路并显示

          await QueryPowerMarkLine(param)
            .then((res) => {
              // console.log(res)
              if (res?.length > 0) {
                res.forEach((item) => {
                  let paramPath = JSON.parse(item.Path);
                  if (paramPath && paramPath.length > 0) {
                    createPoylineItemFun(
                      paramPath,
                      map,
                      item.Colour,
                      item.Width,
                      item.Pellucidity,
                      item.Pattern,
                    );
                  } else {
                    console.log('paramPath绘制的线路', 'paramPath 长度为0！');
                  }
                });
              }
            })
            .catch((err) => {
              console.log('homeMap/QueryPowerMarkLine', err);
            });

          //#endregion

          //#region 场馆数据及图标创建

          await GetActiVenueInfo(param)
            .then((res) => {
              // console.log(res)
              if (res && res.length != 0) {
                store.dispatch('HospVenuAmbuModule/saveVenueAct', res);
              } else {
                console.log('homeMap/GetActiVenueInfo', '场馆数据返回为空');
              }
            })
            .catch((err) => {
              console.log('homeMap/GetActiVenueInfo', err);
            });

          // 场馆下的医疗点图标创建 await必须加，不然venueMedicalPointArrVx为空---satrt
          // console.log(venueMedicalPointArrVx.value)
          let venueMedicalPointArr = venueMedicalPointArrVx.value;
          venueMedicalPointArr.forEach((item) => {
            // console.log(item)
            // 经纬度转换过了
            if (item.online) {
              let color = '#9933ff';
              let iconUrl = venueMedicalPointIconUrl;
              if (item.online == false) {
                iconUrl = venueMedicalPointIconUrl_noLine;
                color = '#767676';
              } else {
                iconUrl = venueMedicalPointIconUrl;
                color = '#9933ff';
              }
              let marker = CreateMark(
                iconUrl,
                50,
                50,
                item.lng,
                item.lat,
                'venue-medical-point-online',
                item.id,
                item.name,
                undefined,
                color,
              );
              // 图标存进数组
              compState.markerList.push(marker);
              // 监听图标点击
              marker.addEventListener('click', async function () {
                // console.log(marker)
                var venueMedicalPointid = marker.id;
                let medicalInfo = {};
                await QueryMedicalPointUserList({
                  medicalPointCode: venueMedicalPointid,
                })
                  .then((res) => {
                    // console.log(res)
                    medicalInfo = res;
                  })
                  .catch((err) => {
                    console.log(err);
                  });
                // 设置中心点坐标和地图级别
                map.flyTo(new BMapGL.Point(item.lng, item.lat), 20);
                let opts = {
                  title: '医疗点信息',
                  width: 300,
                  height: 'auto',
                };
                let myinfoWindow = new BMapGL.InfoWindow(
                  venueMedicalPointContentcopy(medicalInfo),
                  opts,
                );
                this.openInfoWindow(myinfoWindow);
              });
              // 1s后将医院图标添加到地图
              let timer = setTimeout(() => {
                map.addOverlay(marker);
                clearTimeout(timer);
              }, 600);
            }
          });

          //#endregion

          //#region 非保障车辆数据

          await QueryNotGuaranteeAmb({ RoleCode: userInfoVx.value.RoleCode })
            .then((res) => {
              // console.log('res/QueryNotGuaranteeAmb', res)
              // 缓存到vuex
              if (res && res.length > 0)
                store.dispatch(
                  'HospVenuAmbuModule/saveNotGuaranteeAmbAct',
                  res,
                );
            })
            .catch((err) => {
              console.log('err', err);
            });

          //#endregion

          //#region 8s定时循环刷新车辆位置及状态信息

          compState.ambuTimer = setInterval(async () => {
            console.log('homeMap/open车辆循环刷新定时器！');
            // compState.ambuTimer = setTimeout(() => {
            // 获取地图上所有标注
            let mapOverlays = map.getOverlays();
            // console.log(mapOverlays)
            // 保障车辆
            await GetAmbulanceInfo(param)
              .then((res) => {
                // console.log(res)
                store.dispatch('HospVenuAmbuModule/saveAmbulanceAct', res);
                // compState.ambulanceTreeRemote = ambulanceTreeRemoteVx.value;
                // 先获取图标中的车辆类型的标注
                let ambuMarkerArr = mapOverlays.filter((item) => {
                  // console.log(item.clas)
                  return (
                    item.clas == 'taskvehicle' ||
                    item.clas == 'onvehicle' ||
                    item.clas == 'notaskvehicle'
                  );
                });
                // console.log(ambuMarkerArr)

                ambuMarkerArr.forEach((makerItem) => {
                  res.forEach((item) => {
                    if (makerItem.id == item.Code) {
                      // 转换经纬度
                      let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat);
                      // console.log(makerItem)
                      // 设置位置
                      makerItem.setPosition(
                        new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat),
                      );
                      // 设置旋转角度
                      makerItem.setRotation(item.Direction);
                      // 获取图标文本标注对象，方便设置样式
                      let label = makerItem.getLabel();
                      // 根据车辆状态设置车辆图标
                      switch (item.StateCode) {
                        // 任务中
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 101:
                        case 102:
                          // let taskVehicleIcon = new BMapGL.Icon(taskVehicleIconUrl, new BMapGL.Size(70, 70))
                          let taskVehicleIcon = new BMapGL.Icon(
                            taskVehicleIconUrl,
                            new BMapGL.Size(30, 45),
                          );
                          makerItem.setIcon(taskVehicleIcon);
                          // console.log(makerItem.getLabel())
                          // 设置文本标注颜色
                          label.setStyle({ color: 'red' });
                          break;
                        // 待命中
                        case 6:
                        case 7:
                          // let ontaskVehicleIcon = new BMapGL.Icon(ontaskVehicleIconUrl, new BMapGL.Size(70, 70))
                          let ontaskVehicleIcon = new BMapGL.Icon(
                            ontaskVehicleIconUrl,
                            new BMapGL.Size(30, 45),
                          );
                          makerItem.setIcon(ontaskVehicleIcon);
                          label.setStyle({ color: 'blue' });
                          break;
                        // 暂停调用
                        case 8:
                        case 9:
                          // let notaskVehicleIcon = new BMapGL.Icon(ontaskVehicleIconUrl, new BMapGL.Size(70, 70))
                          let notaskVehicleIcon = new BMapGL.Icon(
                            ontaskVehicleIconUrl,
                            new BMapGL.Size(30, 45),
                          );
                          makerItem.setIcon(notaskVehicleIcon);
                          label.setStyle({ color: 'gray' });
                          break;
                        default:
                          break;
                      }
                    }
                  });
                });
                //#region 更新车辆标签图层 不用了
                // console.log(compState.isShowVenueLayers)
                // 当车辆标签图层存在数据并且显示时，定时器生效，刷新车辆
                if (compState.isShowVenueLayers) {
                  let ambulayerData = compState.ambuLayer.getData();
                  if (ambulayerData.length > 0) {
                    // 获取场馆名称
                    let venueName = ambulayerData[0].venueName;
                    //  console.log(venueName)
                    compState.layerdata = [];
                    // 遍历场馆下车辆(compState.venueAmbu是第一次点击缓存的数据，只要上面的if条件通过compState.venueAmbu不为空)
                    // res 是所有的车辆，根据车辆编码筛选某场馆的车辆
                    // console.log("场馆车辆：", compState.venueAmbu)
                    res.forEach((resItem) => {
                      compState.venueAmbu.forEach((item) => {
                        if (resItem.Code == item.Code) {
                          // console.log(item)
                          let newItem = wgs84togcj02tobd09(
                            resItem.Lng,
                            resItem.Lat,
                          );
                          compState.layerdata.push({
                            ambucode: item.Code,
                            venueName: venueName,
                            geometry: {
                              type: 'Point',
                              coordinates: [newItem.Lng, newItem.Lat],
                            },
                            properties: {
                              text: item.Name + '\n' + venueName,
                            },
                          });
                        }
                      });
                    });
                    // layer重新设置数据
                    compState.ambuLayer.setData(compState.layerdata);
                    console.log('重新设置了车辆标签图层！');
                  }
                }
                //#endregion
              })
              .catch((err) => {
                console.log(err);
              });

            // 非保障车辆数据
            await QueryNotGuaranteeAmb({ RoleCode: userInfoVx.value.RoleCode })
              .then((res) => {
                let ambuMarkerArrNoGuarantee = mapOverlays.filter((item) => {
                  // console.log(item.clas)
                  return (
                    item.clas == 'notguarantee-task-vehicle' ||
                    item.clas == 'notguarantee-task-vehicle'
                  );
                });
                // console.log('res/QueryNotGuaranteeAmb', res)
                // 缓存到vuex
                if (res && res.length > 0) {
                  store.dispatch(
                    'HospVenuAmbuModule/saveNotGuaranteeAmbAct',
                    res,
                  );
                  ambuMarkerArrNoGuarantee.forEach((makerItem) => {
                    res.forEach((item) => {
                      if (makerItem.id == item.ambCode) {
                        // 转换经纬度
                        let LngLatObj = wgs84togcj02tobd09(
                          item.ambLng,
                          item.ambLat,
                        );
                        // console.log(makerItem)
                        // 设置位置
                        makerItem.setPosition(
                          new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat),
                        );
                        // 设置旋转角度
                        makerItem.setRotation(item.ambDirection);
                        // 获取图标文本标注对象，方便设置样式
                        let label = makerItem.getLabel();
                        // 根据车辆状态设置车辆图标
                        switch (item.ambStateCode) {
                          // 任务中
                          case 1:
                            makerItem.setIcon(
                              new BMapGL.Icon(
                                notguaranteeTaskVehicleUrl,
                                new BMapGL.Size(17, 34),
                              ),
                            );
                            // console.log(makerItem.getLabel())
                            // 设置文本标注颜色
                            label.setStyle({ color: 'red' });
                            break;
                          // 待命中
                          case 2:
                            makerItem.setIcon(
                              new BMapGL.Icon(
                                notguaranteeOntaskVehicleUrl,
                                new BMapGL.Size(17, 34),
                              ),
                            );
                            label.setStyle({ color: 'green' });
                            break;
                          default:
                            break;
                        }
                      }
                    });
                  });
                }
              })
              .catch((err) => {
                console.log('err', err);
              });
          }, 8000);

          //#endregion

          // 初始化城市下拉框和场馆下拉框 跳转------------------------------------start
          // console.log(ACVCodesVx.value)
          // console.log(cityInfoVx.value)
          // console.log(venueInfoVx.value)
          let { selectType } = ACVCodesVx.value;
          if (
            selectType == 'selectCity' &&
            cityInfoVx.value != null &&
            cityInfoVx.value?.Code != -1
          ) {
            await map.setCenter(cityInfoVx.value?.name);
          } else if (
            selectType == 'selectVenue' &&
            venueInfoVx.value != null &&
            venueInfoVx.value?.Code != -1
          ) {
            let LngLatObj = wgs84togcj02tobd09(
              venueInfoVx.value?.Lng,
              venueInfoVx.value?.Lat,
            );
            map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 17);
          }
          // ------------------------------------------------------------------end
        } catch (error) {
          console.log('homeMap', error);
        }
      });
    });
    onUnmounted(() => {
      clearInterval(compState.ambuTimer);
      // clearTimeout(compState.ambuTimer)
      console.log('homeMap/clear车辆循环刷新定时器！');
    });
    const refState = toRefs(compState);
    return {
      // 状态
      ...refState,
      map,
      medicalRooms,
      doctorsVx,
      nursesVx,
      ambulancesVx,
      // 事件
      InitMyMap,
      CreateMark,
      filterNode,
      // 医院
      handShowHospital,
      handleCloseHospital,
      handleHospitalNode,
      // 车辆
      handleShowAmbulance,
      handleCloseAmbulanceInfo,
      handleAmbulanceInfoNode,
      // 药品耗材
      handleSurplus,
      handleDrugNodeClick,
      closeDrugConsumClick,
      receiveDACRequestRes,
      // 医务室
      handleShowMedicalRoomPoint,
      handlemedicalRoomPointNodeClick,
      handleCloseMedicalRoomPoint,
      // 医生/护士
      handleShowUserInfo,
      handleUserInfoNodeClick,
      handleCloseUserInfo,
      // 图例
      handleShowWhichPar,
      handleShowWhichNotGuaranteeEmit,
      // 地图右侧
      handleLinePosition,
      handleClearLine,
      // 显隐藏按钮
      handleShowLeft,
      handleHideAmbuTag,
      handleSendHospital,
      handleCloseSendHospital,
      handleAceptPatient,
      handleOrdinaryPattern,
      handleDiurnalPattern,
      handleDarkPattern,
    };
  },
};
</script>
<style scoped>
.map {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 0;
}

/* 地图左侧 */
.map_left {
  position: absolute;
  margin: 3px;
  z-index: 1;
}

/* 地图右侧 */
.map_right {
  width: 520px;
  position: absolute;
  right: 3px;
  margin-top: 3px;
}

.fk_home .custom_dialog {
  position: absolute;
  height: 500px;
  width: 320px;
  background: #fff;
  left: 310px;
  top: 65px;
  z-index: 9;
}

/* .fk_home .drug_venue_dialog {
  position: absolute;
  height: 300px;
  width: 220px;
  background: #fff;
  left: 260px;
  top: 400px;
} */

/* 地图图标显示窗口 */
:deep(.BMap_bubble_pop) {
  padding: 0 !important;
}

:deep(.BMap_bubble_top) {
  background: #758bfd !important;
}

:deep(.BMap_bubble_top .BMap_bubble_title) {
  margin-left: 5px !important;
}

/* // 去掉文字那行，添加CSS即可 */
:deep(.BMap_cpyCtrl) {
  display: none;
}

.fk_home .tree_icon {
  cursor: pointer;
  position: relative;
  margin: 5px;
}

.fk_home .tree_icon:hover {
  color: #758bfd;
}

.fk_home .patient-custom-dialog {
  position: absolute;
  right: 550px;
  top: 100px;
  background-color: #fff;
  width: 900px;
  border: 1px solid rgba(225, 225, 225, 0.5);
  z-index: 9;
}
</style>
